<template>
  <view class="container">
    <!-- 页面内容区域 -->
    <view class="page-content">
      <index 
        v-if="PageCur == 'index'" 
        @Showorder="Showorder"
        :key="'index-' + refreshKey.index"
      ></index>
      
      <song 
        v-if="PageCur == 'song'"
        :key="'song-' + (refreshKey.song || 0)"
      ></song>
      
      <order 
        v-if="PageCur == 'order'"
        :key="'order-' + refreshKey.order"
      ></order>
      
      <me 
        v-if="PageCur == 'me'"
        :key="'me-' + refreshKey.me"
        @refresh="handleMeRefresh"
      ></me>
    </view>

    <!-- 底部导航栏 -->
    <view class="tabbar-container">
      <view class="cu-bar tabbar bg-white shadow foot">
        <view 
          class="action" 
          @tap="NavChange" 
          data-cur="index"
          :class="{ 'active': PageCur == 'index' }"
        >
          <view class='cuIcon-cu-image'>
            <image 
              v-if="PageCur == 'index'" 
              src="../../static/tabBar/index_cur.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
            <image 
              v-else 
              src="../../static/tabBar/index.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
          </view>
          <view :class="PageCur == 'index' ? 'color_main' : 'text-gray'">首页</view>
        </view>

        <view 
          class="action" 
          @tap="NavChange" 
          data-cur="song"
          :class="{ 'active': PageCur == 'song' }"
        >
          <view class='cuIcon-cu-image'>
            <image 
              v-if="PageCur == 'song'" 
              src="../../static/me/icon/yinle.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
            <image 
              v-else 
              src="../../static/me/icon/yinle.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
          </view>
          <view :class="PageCur == 'song' ? 'color_main' : 'text-gray'">点歌</view>
        </view>

        <view 
          class="action" 
          @tap="NavChange" 
          data-cur="order"
          :class="{ 'active': PageCur == 'order' }"
        >
          <view class='cuIcon-cu-image'>
            <image 
              v-if="PageCur == 'order'" 
              src="../../static/tabBar/order_cur.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
            <image 
              v-else 
              src="../../static/tabBar/order.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
          </view>
          <view :class="PageCur == 'order' ? 'color_main' : 'text-gray'">我的订单</view>
        </view>

        <view 
          class="action" 
          @tap="NavChange" 
          data-cur="me"
          :class="{ 'active': PageCur == 'me' }"
        >
          <view class='cuIcon-cu-image'>
            <image 
              v-if="PageCur == 'me'" 
              src="../../static/tabBar/me_cur.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
            <image 
              v-else 
              src="../../static/tabBar/me.png"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
          </view>
          <view :class="PageCur == 'me' ? 'color_main' : 'text-gray'">个人中心</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/common/request.js';
import index from "./index.vue";
import order from "./order.vue";
import me from "./me.vue";  
import song from "../song/index.vue";

export default {
  components: {
    index,
    order,
    me,
    song
  },
  
  data() {
    return {
      PageCur: 'index',
      refreshKey: {
        index: 0,
        order: 0,
        me: 0,
        song: 0
      },
      pageLoaded: {
        index: false,
        order: false,
        me: false,
        song: false
      }
    };
  },
  onLoad(option) {
    console.log('来自页面:', option || {})
    
    // 确保option存在
    if (!option) {
      option = {};
    }
    
    // 检查store是否存在
    if (!this.$store) {
      console.error('Store未在tabbar中初始化')
      setTimeout(() => {
        if (this.$store) {
          console.log('Store延迟初始化成功')
        }
      }, 100)
    }
    
    // 微信小程序分享菜单
    // #ifdef MP-WEIXIN
    try {
      if (typeof wx !== 'undefined' && wx.showShareMenu) {
        wx.showShareMenu({
          withShareTicket: true
        })
      }
    } catch (error) {
      console.log('微信分享菜单设置失败:', error)
    }
    // #endif
    
    // 处理特殊跳转
    if (option.type == 'matting') {
      uni.navigateTo({
        url: '../main/matting'
      })
      return
    }

    // 如果有指定页面，直接跳转
    if (option.page && ['index', 'order', 'me', 'song'].includes(option.page)) {
      this.PageCur = option.page
    }

    // 标记首页已加载
    this.pageLoaded.index = true
  },

  onShow() {
    this.refreshCurrentPage()
  },

  methods: {
    Showorder(page) {
      console.log('显示页面:', page)
      if (['index', 'order', 'me', 'song'].includes(page)) {
        this.PageCur = page
        this.refreshCurrentPage()
      }
    },

    NavChange(e) {
      const targetPage = e.currentTarget.dataset.cur
      console.log('切换到页面:', targetPage)

      if (this.PageCur === targetPage) {
        this.refreshCurrentPage()
        return
      }

      this.PageCur = targetPage
      this.refreshCurrentPage()
      this.updatePageTitle(targetPage)
    },

    refreshCurrentPage() {
      this.refreshKey[this.PageCur]++
      this.pageLoaded[this.PageCur] = true
      console.log(`刷新${this.PageCur}页面，key: ${this.refreshKey[this.PageCur]}`)
    },

    handleMeRefresh() {
      console.log('个人中心页面请求刷新')
      this.refreshKey.me++
    },

    updatePageTitle(page) {
      let title = ''
      switch(page) {
        case 'index':
          title = '首页'
          break
        case 'order':
          title = '我的订单'
          break
        case 'me':
          title = '个人中心'
          break
        case 'song':
          title = '点歌'
          break
        default:
          title = '首页'
      }
      
      try {
        uni.setNavigationBarTitle({
          title: title
        })
      } catch (error) {
        console.log('设置标题失败:', error)
      }
    },

    // 处理图片加载错误
    handleImageError(e) {
      console.log('图片加载失败:', e)
    },

    refreshPage(page) {
      if (this.refreshKey[page] !== undefined) {
        this.refreshKey[page]++
        console.log(`手动刷新${page}页面`)
      }
    },

    resetAllPages() {
      Object.keys(this.refreshKey).forEach(key => {
        this.refreshKey[key]++
      })
      Object.keys(this.pageLoaded).forEach(key => {
        this.pageLoaded[key] = false
      })
      console.log('重置所有页面')
    }
  }
}
</script>

<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  // height: 100vh;
  background-color: #f5f5f5;
}

.page-content {
  flex: 1;
  position: relative;
  /* 移除 overflow: hidden，让子组件自己处理滚动 */
  /* 移除固定高度，使用 flex: 1 自适应 */
}

.tabbar-container {
  flex-shrink: 0;
  position: relative;
  z-index: 999;
}

.color_main {
  color: #007aff !important;
  font-weight: 600;
}

.text-gray {
  color: #8f8f94;
}

.cu-bar.tabbar {
  padding: 0;
  background-color: #fff;
  border-top: 1rpx solid #e5e5e5;
  height: 120rpx;
  display: flex;
  align-items: center;

  .action {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    padding: 12rpx 0 8rpx;
    transition: all 0.3s ease;
    height: 100%;

    &.active {
      transform: scale(1.05);
    }

    .cuIcon-cu-image {
      width: 48rpx;
      height: 48rpx;
      margin-bottom: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 100%;
        height: 100%;
        display: block;
      }
    }

    view:last-child {
      font-size: 20rpx;
      line-height: 1.2;
      text-align: center;
      transition: color 0.3s ease;
    }

    &:active {
      opacity: 0.7;
    }
  }
}

.foot {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

/* 确保子组件能够正常滚动 */
.page-content > view {
  height: 100%;
  /* 移除 overflow-y: auto，让子组件自己处理 */
}
</style>
